package com.submit.demo.component;

import com.submit.demo.common.api.CommonResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

@Aspect
@Component
@Order(2)
public class BindResultAspect {
    @Pointcut("execution(public * com.submit.demo.controller.*.*(..))")
    public void BindingResult() {
    }

    @Around("BindingResult()")
    public Object doAroud(ProceedingJoinPoint joinPoint) throws Throwable{
        Object[] args =joinPoint.getArgs();
        for(Object arg : args){
            if(arg instanceof BindResult){
                BindingResult result =(BindingResult) arg;
                if(result.hasErrors()){
                    FieldError fieldError = result.getFieldError();
                    if(fieldError != null){
                        return CommonResult.validateFailed(fieldError.getDefaultMessage());
                    }else return CommonResult.validateFailed();
                }
            }
        }
        return joinPoint.proceed();
    }
}
